<template>
  <div id="chat-room">
    <div class="chat-header">
      <div class="chat-header-left">
        <el-input 
          show-word-limit
          type="text"
          placeholder="请输入聊天室的id"
          v-model="chatRoomId"
          :maxlength="ID_LENGTH"
        />
        <el-button type="primary" @click="enterChatRoom">进入聊天室</el-button>
      </div>
      <div>
        <el-button type="danger" @click="disConnected">断开当前聊天室</el-button>
        <el-button type="success" @click="toOperate">创建聊天室</el-button>
      </div>
    </div>
    <div class="chat-content">
      <div class="message-history">
        <h3 v-if="!nowChatRoom.id">未连接任何聊天室</h3>
        <el-scrollbar ref="scrollbarRef" v-if="nowChatRoom.id">
          <div ref="messageDiv">
            <div class="chat-room-title">
              <span>{{ nowChatRoom.name }}</span>
              <span>（{{ chatRoomInfo.count }}人在线）</span>
            </div>
            <div 
              v-for="m in nowChatRoom.messages"
              class="message-item" 
              :class="{
                'message-mine': userStore.user.account == m.account, 
                'message-others': userStore.user.account != m.account, 
              }"
            >
              <div class="wrapper">
                <div class="account">{{ m.account }}，</div>
                <div class="time">{{ formatTime(m.time) }}</div>
                <div class="data">{{ m.data }}</div>
              </div>
            </div>
            <div style="height: 80px;">

            </div>
          </div>
        </el-scrollbar>
      </div>
      <div class="message-send">
        <el-input
          class="input-area"
          :rows="3"
          show-word-limit
          type="textarea"
          placeholder="请输入消息内容"
          v-model="inputMessage"
          :maxlength="300"
        />
        <el-button type="success" @click="sendMessage(inputMessage, 1, false)">发送(Enter)</el-button>
      </div>
    </div>
    <ChatRoomOperate v-if="chatRoomOperating"/>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { ChatRoom } from '../type/entity'
import { getChatRoomById, getChatRooms } from '../request/chatRoom'
import { ElMessage, ElScrollbar } from 'element-plus'
import { useChatRoomStore } from '../store/chatRoom'
import { useUserStore } from '../store/user'
import ChatRoomOperate from '../components/ChatRoom/ChatRoomOperate.vue'
import { storeToRefs } from 'pinia'
import { BASE_URL } from '../util/http'
import { formatTime } from '../util/chore'
interface WsMessage {
  typeId: number
  token: string
  data: string
  chatRoomId: string
  askInfo: boolean
}
interface ChatMessage{
  account: string
  time: number
  data: string
}
interface InfoMessage{
  count: number
}
type ResMessage = ChatMessage | InfoMessage
const userStore = useUserStore()
const chatRoomStore = useChatRoomStore()
const { chatRooms, nowChatRoom, chatRoomOperating } = storeToRefs(chatRoomStore)
const chatRoomInfo = ref({
  count:0
})
const chatRoomId = ref('')
const inputMessage = ref('')
const ID_LENGTH = 50 // 聊天室id的长度
const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>()
const messageDiv = ref<HTMLDivElement>()
let ws:WebSocket|undefined = undefined
function disConnected(){
  if(ws){
    ws.close()
  }
  nowChatRoom.value = {} as ChatRoom
}
function wsConnect(){
  if(ws){
    ws.close()
  }
  // 生成WebSocket对象
  ws = new WebSocket('ws' + BASE_URL.substring(4) + '/wsChatRoom')

  // 为WebSocket添加事件监听
  ws.addEventListener('message', function (event:MessageEvent<string>){
    let rawMessage = JSON.parse(event.data)
    console.log(rawMessage)
    if(rawMessage.account){
      let resMessage = rawMessage as ChatMessage
      nowChatRoom.value.messages.push(resMessage)
      nextTick(() => {
        // 必须要等新消息渲染完毕后再动滚轮
        scrollbarRef.value?.setScrollTop(messageDiv.value?.clientHeight as number)
      })
    }
    else {
      let resMessage = rawMessage as InfoMessage
      chatRoomInfo.value.count = resMessage.count
    }
  })
  ws.addEventListener('open', () => {
    console.log('websocket连接建立完毕')
    sendMessage("ask", 2, true)
  })
  ws.addEventListener('close', function(event){
    console.log('close')
  })
  ws.addEventListener('error', function(event){
    ElMessage({type: 'error', message: 'WebSocket通信出错了'})
  })
}


function sendMessage(data:string, typeId:number, askInfo:boolean){
  if(!ws){
    return 
  }
  if(data == ''){
    ElMessage({type:'warning', message: '发送信息不可以为空'})
    return 
  }
  let wsMessage:WsMessage = {
    typeId,
    data,
    chatRoomId: nowChatRoom.value.id,
    token: localStorage.getItem('token') as string,
    askInfo
  }
  ws.send(JSON.stringify(wsMessage))
  inputMessage.value = ''
}
function enterChatRoom(){
  if(chatRoomId.value.length != ID_LENGTH){
    ElMessage({type: 'warning', message: '请输入正确的id'})
    return
  }
  getChatRoomById(chatRoomId.value).then(
    res => {
      if(res.data.id){
        nowChatRoom.value = res.data
        wsConnect()
      }
      else {
        ElMessage({type:'error', message:'不存在该聊天室'})
      }
    }
  )
}
function toOperate(){
  chatRoomOperating.value = true
}
</script>

<style scoped>

</style>